<?php
namespace app\common\model;

use app\common\library\mstching\YiLian;
use think\facade\Cache;
use hema\wechat\Driver as Wechat;
use hema\device\Driver as Printer;

/**
 * 公众号模型
 */
class Setting extends BaseModel
{
    // 定义表名
    protected $name = 'setting';
    protected $createTime = false;

    // 追加字段
    protected $append = [];

    /**
     * 设置项描述
     */
    private $describe = [
        'web' => '站点设置',
        'wxweb' => '网站应用',
        'webdelivery' => '配送接口',
        'calling' => '云呼叫',
        'foodhelp' => '商户手机端',
        'foodcash' => 'PC收银端',
        'wxpayisp' => '微信支付服务商设置',
        'webpay' => '支付设置',
        'printer' => '打印设备',
        'webtplmsg' => '站点模板消息',
        'storage' => '上传设置',
        //'outapp'=> '外卖平台',
        //'solve' => '结算设置',
        //'register' => '注册设置'
        'mode' => '功能设置',
        'wxapptpl' => '微信小程序订阅消息',
        'wechattpl' => '微信公众号模板消息',
        'trade' => '交易设置',
        'recharge' => '充值设置',
        'delivery' => '配送设置',
        'payment' => '支付设置',
        'subscribe' => '关注回复',//公众号
        'menus' => '公众号菜单',
        'pactsort' => '预约排队设置',
        'pacttable' => '预约订桌设置',
        'grade' => '等级管理',
        'other' => '其它设置',
    ];

    /**
     * 获取器: 转义数组格式
     */
    public function getValuesAttr($value)
    {
        return json_decode($value, true);
    }

    /**
     * 修改器: 转义成json格式
     */
    public function setValuesAttr($value)
    {
        return json_encode($value);
    }

    /**
     * 获取指定项设置
     */
    public static function getItem(string $key, $applet_id = null)
    {
        $data = self::getAll($applet_id);
        return isset($data[$key]) ? $data[$key]['values'] : [];
    }

    /**
     * 获取设置项信息
     */
    public static function detail(string $key,$applet_id = null)
    {
        is_null($applet_id) && $applet_id = self::$applet_id;
        empty($applet_id) && $applet_id = 0;
        // 筛选条件
        $filter = [];
        $filter['key'] = $key;
        $filter['applet_id'] = $applet_id;
        return self::withoutGlobalScope()->where($filter)->find();
    }

    /**
     * 全局缓存: 系统设置
     */
    public static function getAll($applet_id = null)
    {
        $self = new static;
        is_null($applet_id) && $applet_id = $self::$applet_id;
        empty($applet_id) && $applet_id = 0;
        // 筛选条件
        $filter = [];
        $filter['applet_id'] = $applet_id;
        if (!$data = Cache::get('setting_' . $applet_id)) {
            $data = array_column($self::withoutGlobalScope()->where($filter)->select()->toArray(), null, 'key');
            Cache::set('setting_' . $applet_id, $data);
        }
        return array_merge_multiple($self->defaultData(), $data);
    }

    /**
     * 更新系统设置
     */
    public function edit(string $key, array $values, $applet_id = null)
    {
        is_null($applet_id) && $applet_id = self::$applet_id;
        empty($applet_id) && $applet_id = 0;
        //打印机配置
        if($key == 'printer'){
            //易联云获取token
            if((!empty($values['yilianyun']['app_key'])) AND (!empty($values['yilianyun']['app_secret'])) AND empty($values['yilianyun']['access_token'])){
                $dev = new Printer([],$values['yilianyun'],0,'yilianyun');
                $values['yilianyun']['access_token'] = $dev->getToken();
            }
        }
        //公众号菜单
        if($key == 'menus'){
            $wx = new Wechat;
            $result = $wx->creatMenu($values,$applet_id);
            if($result['errcode'] != 0){
                $this->error = 'code：' . $result['errcode'] . '，msg：' . $result['errmsg'];
                return false;
            }
        }
        //关注公众号回复
        if($key == 'subscribe'){
            $values = $this->subscribe($values);
        }
        //如果是设置微信小程序订阅消息
        if($key == 'wxapptpl'){
            $values = $this->wxapptpl($values,$applet_id);
        }

        $model = self::detail($key,$applet_id) ?: $this;
        // 删除系统设置缓存
        Cache::delete('setting_' . $applet_id);
        return $model->save([
            'key' => $key,
            'describe' => $this->describe[$key],
            'values' => $values,
            'applet_id' => $applet_id,
        ]) !== false;
    }

    /**
     * 关注回复内容
     */
    private function subscribe($data)
    {
        if($data['type'] == 'text'){
            $data['content']['media_id'] = ''; 
            $data['content']['title'] = '';
            $data['content']['url'] = '';
            $data['content']['hurl'] = '';
            $data['content']['picurl'] = '';
        }else{
            if(!$material = Material::mediaId($data['content']['media_id'])){
                $this->error = '素材不存在';
                return false; 
            }
            //图片消息
            if($data['type'] == 'image' OR $data['type'] == 'voice'){
                $data['content']['description'] = ''; 
                $data['content']['title'] = '';
                $data['content']['url'] = '';
                $data['content']['hurl'] = '';
                $data['content']['picurl'] = '';
            }
            //视频消息
            if($data['type'] == 'video'){
                //获取视频素材内容
                $data['content']['title'] = $material['name'];
                $data['content']['description'] = $material['introduction'];
                $data['content']['url'] = '';
                $data['content']['hurl'] = '';
                $data['content']['picurl'] = '';
            }
            //图文消息
            if($data['type'] == 'news'){
                //获取视频素材内容
                $data['content']['picurl'] = $material['url'];
                $data['content']['url'] = $data['content']['url'] ? $data['content']['url'] : base_url();
                $data['content']['hurl'] = '';
            }
        }
        return $data;
    }

    /**
     * 餐饮微信订阅消息设置
     */
    private function wxapptpl(array $values,$applet_id)
    {
        //验证是否添加小程序餐饮服务目录
        $wx = new Wechat;
        //获取已设置的服务类目
        $result = $wx->getCategory($applet_id);
        $msg = '未添加餐饮服务场所类目或类目未通过审核';
        $isSet = false;//是否符合设置要求
        if($result['errcode']!=0){
            $this->error = $msg;
            return false;
        }else{
            for($n=0;$n<sizeof($result['categories']);$n++){
                if($result['categories'][$n]['first']==220 AND $result['categories'][$n]['second']==632 AND $result['categories'][$n]['audit_status']==3){
                    $isSet = true;
                    break;
                }
            }
        }
        if(!$isSet){
            $this->error = $msg;
            return false;
        }
        //获取帐号下的模板列表
        $result = $wx->getTemplateTpl($applet_id);
        if($result['errcode']==0){
            //循环删除订阅消息模板
            for($n=0;$n<sizeof($result['data']);$n++){
                $wx->delTemplateTpl($applet_id,$result['data'][$n]['priTmplId']);
            }
        }
        //添加商家接单通知
        $tid = '7942';
        $kidlist = [2,6,7,10,5];
        $desc ='商家接单通知';
        $result = $wx->addTemplateTpl($applet_id,$tid,$kidlist,$desc);
        if($result['errcode']==0){
            $values['receive'] = $result['priTmplId'];
        }
        //添加骑手取货通知
        $tid = '8927';
        $kidlist = [1,2,4];
        $desc ='骑手取货通知';
        $result = $wx->addTemplateTpl($applet_id,$tid,$kidlist,$desc);
        if($result['errcode']==0){
            $values['horseman'] = $result['priTmplId'];
        }
        //添加订单完成通知
        $tid = '677';
        $kidlist = [13,11,14,12,5];
        $desc ='订单完成通知';
        $result = $wx->addTemplateTpl($applet_id,$tid,$kidlist,$desc);
        if($result['errcode']==0){
            $values['finish'] = $result['priTmplId'];
        }
        //添加取餐提醒
        $tid = '250';
        $kidlist = [23,12,30,16,7];
        $desc ='取餐提醒';
        $result = $wx->addTemplateTpl($applet_id,$tid,$kidlist,$desc);
        if($result['errcode']==0){
            $values['take'] = $result['priTmplId'];
        }
        //添加订单配送通知
        $tid = '584';
        $kidlist = [1,2,15,4,5];
        $desc ='订单配送通知';
        $result = $wx->addTemplateTpl($applet_id,$tid,$kidlist,$desc);
        if($result['errcode']==0){
            $values['delivery'] = $result['priTmplId'];
        }
        //退款状态通知
        $tid = '8995';
        $kidlist = [1,2,4,5];
        $desc ='退款状态通知';
        $result = $wx->addTemplateTpl($applet_id,$tid,$kidlist,$desc);
        if($result['errcode']==0){
            $values['refund'] = $result['priTmplId'];
        }
        return $values;
    }
    
   

    /**
     * 默认配置
     */
    public function defaultData()
    {
        return [
            'web' => [
                'key' => 'web',
                'describe' => '站点设置',
                'values' => [
                    'name' => '河马云店',//网站名称
                    'domain' => '', //网站域名
                    'icp' => '',    //备案号
                    'address' => '',//地址
                    'keywords' => '',   //关键字
                    'description' => '',    //描述
                    'company' => '',//公司名称
                    'phone' => '',//联系电话
                    'open_id' => '',    //管理员微信ID
                    'wxmap' => '',  //微信地图KEY
                    'copyright' => '©河马云店'  //小程序显示版权
                ],
            ],
            'wxweb' => [
                'key' => 'wxweb',
                'describe' => '网站应用',
                'values' => [
                    'app_id' => '', //公众号APPID
                    'app_secret' => '', //密钥
                ],
            ],
            // 上传设置
            'storage' => [
                'key' => 'storage',
                'describe' => '上传设置',
                'values' => [
                    'default' => 'local',
                    'engine' => [
                        'local' => null,
                        'qiniu' => [
                            'bucket' => '',
                            'access_key' => '',
                            'secret_key' => '',
                            'domain' => 'http://'
                        ],
                        'aliyun' => [
                            'bucket' => '',
                            'access_key_id' => '',
                            'access_key_secret' => '',
                            'domain' => 'http://'
                        ],
                        'qcloud' => [
                            'bucket' => '',
                            'region' => '',
                            'secret_id' => '',
                            'secret_key' => '',
                            'domain' => 'http://'
                        ],
                    ]
                ],
            ],
            'webdelivery' => [
                'key' => 'webdelivery',
                'describe' => '配送接口',
                'values' => [
                    'uu' => [
                        'is_open' => '0',//是否开启
                        'pay_mode' => '0',//扣费模式,0余额，1分账
                        'api_url' => 'https://openapi.uupt.com',//请求接口
                        'app_id' => '',//应用ID
                        'app_key' => '',//应用密钥
                        'open_id' => ''//账户ID
                    ],
                    'sf' => [
                        'is_open' => '0',//是否开启
                        'pay_mode' => '0',//扣费模式,0余额，1分账
                        'api_url' => 'https://openic.sf-express.com',//请求接口
                        'app_key' => '',//开发者ID
                        'app_secret' => ''//开发者密钥
                    ],
                    'dada' => [
                        'is_open' => '0',//是否开启
                        'pay_mode' => '0',//扣费模式,0余额，1分账
                        'api_url' => 'https://newopen.imdada.cn',//请求接口
                        'app_key' => '',//开发者ID
                        'app_secret' => '',//开发者密钥
                        'source_id' => '' //商户号
                    ],
                    'make' => [
                        'is_open' => '0',//是否开启
                        'pay_mode' => '0',//扣费模式,0余额，1分账
                        'api_url' => 'https://t.xiaomawei.com',//请求接口
                        'token' => '',//令牌
                        'appid' => '',//应用ID
                    ]
                ],
            ],
            'foodhelp' => [
                'key' => 'foodhelp',
                'describe' => '商家助手',
                'values' => [
                    'app_name' => '河马云店',   //标题名称
                    'app_id' => '', //公众号APPID
                    'app_secret' => '', //密钥
                    'share_title' => '河马云店',
                    'share_image' => base_url().'assets/img/no_pic.jpg',//分享图片
                    'logo' => base_url().'assets/img/no_pic.jpg',//分享图片
                    'copyright' => '©河马科技'//小程序显示版权
                ],
            ],
            'foodcash' => [
                'key' => 'foodcash',
                'describe' => 'PC收银端',
                'values' => [
                    'name' => '河马云店收银系统',   //标题名称
                    'bg_img' => base_url().'assets/img/login_bg.jpg',//登录背景图片
                    'logo_img' => base_url().'assets/img/login_bg2.jpg',//登录logo图片
                    'copyright' => '©河马科技'//显示版权
                ],
            ],
            'pactsort' => [
                'key' => 'pactsort',
                'describe' => '预约排队设置',
                'values' => [
                    'is_open' => 0,
                    'is_print' => 0,
                    'is_call' => 0,
                    'range' => 50,
                ],
            ],
            'pacttable' => [
                'key' => 'pacttable',
                'describe' => '预约订桌设置',
                'values' => [
                    'is_open' => 0,
                    'is_print' => 0,
                    'range' => 50,
                ],
            ],
            'grade' => [
                'key' => 'grade',
                'describe' => '等级设置设置',
                'values' => [
                    0 => [
                        'score' => 0 , 'gift' => []
                    ],
                    1 => [
                        'score' => 100 , 'gift' => []
                    ],
                    2 => [
                        'score' => 500 , 'gift' => []
                    ],
                    3 => [
                        'score' => 1000 , 'gift' => []
                    ],
                    4 => [
                        'score' => 3000 , 'gift' => []
                    ],
                    5 => [
                        'score' => 5000 , 'gift' => []
                    ],
                ],
            ],
            /*'outapp' => [
                'key' => 'outapp',
                'describe' => '外卖平台',
                'values' => [
                    'wx' => [
                        'app_id' => '', //APPID
                        'app_secret' => '', //密钥
                    ]
                ],
            ],
            'solve' => [
                'key' => 'solve',
                'describe' => '结算设置',
                'values' => [
                    'mode' => 'fixed',  //结算方式 ratio=比例提拥 ，fixed=固定金额
                    'value' => '0'  //数值
                ],
            ],
            'register' => [
                'key' => 'register',
                'describe' => '注册设置',
                'values' => [
                    'prefix' => 'hema', //账号前缀
                    'examine' => 0,  //快速注册小程序审核费
                    'wxapp_auth' => 0, //快速注册小程序超管是否审核
                    'out_auth' => 0   //外卖平台入驻超管是否审核
                ],
            ],*/
            'wxpayisp' => [
                'key' => 'wxpayisp',
                'describe' => '微信支付服务商设置',
                'values' => [
                    'app_id' => '', //公众号APPID
                    'mch_id' => '',  //商户号
                    'api_key' => '', //密钥
                    'api_v3_key' => '',   //APIv3密钥
                    'cert_id' => '',
                    'cert_pem' => '',
                    'key_pem' => ''
                ],
            ],
            'webpay' => [
                'key' => 'webpay',
                'describe' => '支付设置',
                'values' => [
                    'divide' => [ //交易分佣
                        'mode' => 'unify',//抽取模式unify=统一模式，order=订单类型,
                        'extract' => '0',//统一抽取比例0-30，单位百分，0为不抽取
                        'order' => [
                            'tang' => '0',//堂食抽取比例
                            'waimai' => '0',//外卖抽取比例
                            'ziqu' => '0',//自取订单抽取比例
                        ],
                        'is_delivery' => '0',//包含配送费
                        'agent_fee' => '0',//抽取分账总额的百分比，0-100，0为不抽取，100抽取全部。
                    ],
                    'cost' => [
                        'cash_mode' => 'fixed',//用户提现手续费模式 fixed=固定 ratio=比例 
                        'cash_fee' => 0,//手续费数值
                        'applet_fee' => 0,//小程序审核费0不收取
                    ],
                    'wx' => [
                        'name' => '',//商户全称
                        'app_id' => '', //微信应用
                        'mch_id' => '',//商户号
                        'api_key' => '',//密钥
                        'is_sub' => 0,
                        'cert_pem' => '', //apiclient_cert.pem 证书
                        'key_pem' => '', //apiclient_key.pem 密钥
                    ]
                ]
            ],
            'calling' => [
                'key' => 'calling',
                'describe' => '云呼叫',
                'values' => [
                    'api_url' => '',    //请求接口
                    'app_key' => '',  //密钥
                    'app_secret' => '', //密钥
                ],
            ],
            'printer' => [
                'key' => 'printer',
                'describe' => '打印设备',
                'values' => [
                    //对对机
                    'mstching' => [
                        'api_url' => 'http://www.open.mstching.com',//请求接口
                        'app_key' => '',//开发者ID
                        'app_secret' => ''//开发者密钥
                    ],
                    //飞鹅
                    'feieyun' => [
                        'api_url' => 'http://api.feieyun.cn/Api/Open/',//请求接口
                        'app_key' => '',//开发者ID
                        'app_secret' => ''//开发者密钥
                    ],
                    //易联云
                    'yilianyun' => [
                        'api_url' => 'https://open-api.10ss.net/',//请求接口
                        'app_key' => '',//开发者ID
                        'app_secret' => '',//开发者密钥
                        'access_token' => ''//access_token
                    ],
                    //大趋
                    'daqu' => [
                        'api_url' => '',//请求接口
                        'app_key' => '',//开发者ID
                        'app_secret' => ''//开发者密钥
                    ]
                ],
            ],
            'webtplmsg' => [
                'key' => 'webtplmsg',
                'describe' => '模板消息',
                'values' => [
                    'new_order' => '',    //新订单通知
                    'examine' => '',  //审核状态通知
                    'balance' => '',  //账户资金变动提醒
                    'apply' => '',    //申请受理通知
                    'deduction' => '',    //扣费失败通知
                    'testing' => '',  //试用申请成功通知
                    'refund' => '',   //退款发起通知
                    'grab' => '',   //骑手抢单通知
                ],
            ],
            'payment' => [
                'key' => 'payment',
                'describe' => '支付设置',
                'values' => [
                    'wx' => [
                        'app_id' => '', //微信应用
                        'is_sub' => 0, //是否为特约商户
                        'mch_id' => '',//商户号
                        'api_key' => '',//密钥
                        'cert_pem' => '', //apiclient_cert.pem 证书
                        'key_pem' => '' //apiclient_key.pem 密钥
                    ],
                    'postpaid' => [0,0,0]
                ]
            ],
            'trade' => [
                'key' => 'trade',
                'describe' => '交易设置',
                'values' => [
                    'order' => [
                        'time' => '10',//任务执行间隔
                        'close_time' => '60',//未支付订单关闭时间
                        'delivery_time' => '60',//已配送订单自动配送完成时间
                        'receive_time' => '60', //配送完毕订单用户自动确认收货时间 
                        'cmt_time' => '1440', //收货订单用户自动评价时间
                        'refund_time' => '0' //退款订单自动退款时间
                    ],
                    'freight_rule' => '10',
                ]
            ],
            'delivery' => [
                'key' => 'delivery',
                'describe' => '配送设置',
                'values' => [
                    'delivery_range' => '3000', //配送范围
                    'free_range' => '0',        //免费配送范围
                    'delivery_price' => '5',    //配送费用
                    'min_price' => '15',        //起送价格
                ]
            ],
            'other' => [
                'key' => 'other',
                'describe' => '其它设置',
                'values' => [
                    'bind_phone' => '1',//登录小程序是否强制用户绑定手机号
                    'order_export' => 'col', //订单导出样式 col竖排，row横排
                ]
            ],
            'menus' => [
                'key' => 'menus',
                'describe' => '公众号菜单',
                'values' => [
                /*  0 => [
                        "type" => "view",
                        "name" => "一级菜单",
                        "sub_button" => [
                            0 => [
                                "type" => "click",
                                "name" => "二级菜单",
                                "key" => "关键字"
                            ],
                        ],
                        "url" => base_url()
                    ]*/
                ],
            ],
            'subscribe' => [
                'key' => 'subscribe',
                'describe' => '关注回复',
                'values' => [
                    'is_open' => 1,     //是否开启 0=关闭，1=开启
                    'type' => 'text',   //消息类型 text=文字消息,image=图片消息,news=图文消息,voice=声音消息
                    'content' => [
                        'media_id' => '',//素材
                        'title' => '',//标题
                        'description' => '谢谢关注',//描述或回复内容
                        'url' => '',//链接网址
                        'hurl' => '',//音乐缩略图
                        'picurl' => ''//图片网络地址
                    ]
                ]
            ],
            'wxapptpl' => [
                'key' => 'wxapptpl',
                'describe' => '微信小程序订阅消息',
                'values' => [
                    'receive' => '',//商家接单通知
                    'horseman' => '',//骑手取货通知
                    'delivery' => '',  //订单配送通知
                    'take' => '',  //取餐提醒
                    'finish' => '',  //订单完成通知
                    'refund' => '',  //退款状态通知
                ],
            ],
            'wechattpl' => [
                'key' => 'wechattpl',
                'describe' => '微信公众号模板消息',
                'values' => [
                    'receive' => '',//商家接单通知
                    'horseman' => '',//骑手取货通知
                    'delivery' => '',  //订单配送通知
                    'take' => '',  //取餐提醒
                    'finish' => '',  //订单完成通知
                    'refund' => '',  //退款状态通知
                ],
            ],
            'recharge' => [
                'key' => 'recharge',
                'describe' => '充值设置',
                'values' => [
                    'is_open' => 1,     //是否开启
                    'is_custom' => 1,   //是否允许用户自定义金额
                    'is_match_plan' => 1,   //是否自动匹配套餐
                    'describe' => '1. 账户充值仅限微信在线方式支付，充值金额实时到账；
2. 账户充值套餐赠送的金额即时到账；
3. 账户余额有效期：自充值日起至用完即止；
4. 若有其它疑问，可拨打客服电话400-000-1234', //充值说明
                ],
            ],
        ];
    }

}
